package cn.thornbird.orgsync.helper.converter;

import cn.thornbird.orgsync.helper.AppHelper;
import cn.thornbird.orgsync.model.AppDepartmentData;
import cn.thornbird.orgsync.model.AppUserData;
import cn.thornbird.orgsync.model.netease.AccountInfo;
import cn.thornbird.orgsync.model.netease.AccountList;
import cn.thornbird.orgsync.model.netease.UnitList;
import org.apache.commons.lang3.StringUtils;

import java.util.HashMap;

public class NeteaseConverter extends DataConverter<UnitList.UnitItem, AccountList.Account, AccountInfo> {

    @Override
    public AppDepartmentData parseDepartment(UnitList.UnitItem department) {
        AppDepartmentData departmentData = new AppDepartmentData();
        departmentData.setId(department.getUnitId());
        departmentData.setParentId(department.getUnitParentId());
        departmentData.setName(department.getUnitName());
        departmentData.setOrder(department.getRank());
        return departmentData;
    }

    @Override
    public AppUserData parseUser(AccountList.Account user) {
        if (user == null) {
            return null;
        }

        AppUserData userData = new AppUserData();
        userData.setId(user.getAccountName());
        userData.setEmployeeNo(user.getJobNumber());
        userData.setName(user.getName());
        if (user.getGender() != null) {
            userData.setGender(user.getGender().intValue() == 0 ? 1 : (user.getGender().intValue() == 1 ? 2 : 0));
        }
        userData.setMobile(user.getMobile());
        userData.setEmail(user.getAccountName() + "@" + user.getDomain());
        userData.setTelephone(user.getTel());
        userData.setTitle(user.getJob());

        userData.setDepartments(new HashMap<>());
        if (user.getUnitList() != null) {
            for (String unitId : user.getUnitList()) {
                userData.getDepartments().put(unitId, new AppUserData.DepartmentInfo());
            }
        }

        return userData;
    }

    @Override
    public AccountInfo toUserInfo(AppUserData userData) {
        AccountInfo accountInfo = new AccountInfo();
        accountInfo.setAccountName(userData.getId());
        accountInfo.setJobNumber(userData.getEmployeeNo());
        accountInfo.setName(userData.getName());
        if (userData.getGender() != null) {
            accountInfo.setGender(userData.getGender().intValue() == 1 ? 0 :
                    (userData.getGender().intValue() == 2 ? 1 : 2));
        }
        accountInfo.setMobile(AppHelper.getPureMobile(userData.getMobile()));
        accountInfo.setTel(userData.getTelephone());
        accountInfo.setJob(userData.getTitle());
        accountInfo.setDepartments(userData.getDepartments(), userData.getMainDepartmentId());
        return accountInfo;
    }

}
